package org.dromara.demo.util;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FileTransUtils {
    public static void doc2pdf(File file, String outPath) throws Exception{
        FileInputStream fis = new FileInputStream(file);
        Document document = new Document(fis);
        removeWaterMark();
        if (!checkDirectory(outPath)) {
            throw new Exception("创建目录失败");
        }
        document.save(outPath, SaveFormat.PDF);
    }

    public static boolean checkDirectory(String filePath) {
        File file = new File(filePath);
        if (file.isDirectory()) {
            return true;
        } else {
            File dir = file.getParentFile();
            if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
                System.out.println(String.format("创建目录%s失败:", dir.getAbsolutePath()));
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * 去除水印
     * 使用反射替换变量
     * @return
     */
    private static void removeWaterMark() throws Exception {
        Class<?> aClass = Class.forName("com.aspose.words.zzXyu");
        Field zzZXG = aClass.getDeclaredField("zzZXG");
        zzZXG.setAccessible(true);
        Field modifiersField = zzZXG.getClass().getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(zzZXG, zzZXG.getModifiers() & ~Modifier.FINAL);
        zzZXG.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 68});
    }
}
